<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Role;
use App\Models\OperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    /**
     * 构造函数，设置中间件
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:admin');
    }

    /**
     * 显示用户列表
     */
    public function index()
    {
        $users = User::with('roles')->paginate(10);
        return view('users.index', compact('users'));
    }

    /**
     * 显示创建用户表单
     */
    public function create()
    {
        $roles = Role::all();
        return view('users.create', compact('roles'));
    }

    /**
     * 保存新创建的用户
     */
    public function store(Request $request)
    {
        $request->validate([
            'username' => 'required|string|max:50|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'roles' => 'required|array',
            'roles.*' => 'exists:roles,id'
        ]);

        $user = User::create([
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'status' => true
        ]);
        x([2,$user]);
        $user->roles()->attach($request->roles);

        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'create',
            'target_type' => 'user',
            'target_id' => $user->id,
            'content' => "创建用户：{$user->username}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('users.index')->with('success', '用户创建成功');
    }

    /**
     * 显示编辑用户表单
     */
    public function edit(User $user)
    {
        $roles = Role::all();
        return view('users.edit', compact('user', 'roles'));
    }

    /**
     * 更新用户信息
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'username' => ['required', 'string', 'max:50', Rule::unique('users')->ignore($user->id)],
            'roles' => 'required|array',
            'roles.*' => 'exists:roles,id',
            'status' => 'required|boolean'
        ]);

        $user->update([
            'username' => $request->username,
            'status' => $request->status
        ]);

        $user->roles()->sync($request->roles);

        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'update',
            'target_type' => 'user',
            'target_id' => $user->id,
            'content' => "更新用户：{$user->username}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('users.index')->with('success', '用户更新成功');
    }

    /**
     * 删除用户
     */
    public function destroy(User $user)
    {
        // 不允许删除自己
        if ($user->id === Auth::id()) {
            return back()->with('error', '不能删除当前登录的用户');
        }

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'delete',
            'target_type' => 'user',
            'target_id' => $user->id,
            'content' => "删除用户：{$user->username}",
            'ip' => request()->ip()
        ]);

        // 删除用户
        $user->delete();

        return redirect()->route('users.index')->with('success', '用户删除成功');
    }

    /**
     * 显示重置密码表单
     */
    public function showResetPasswordForm(User $user)
    {
        return view('users.reset-password', compact('user'));
    }

    /**
     * 重置用户密码
     */
    public function resetPassword(Request $request, User $user)
    {
        $request->validate([
            'password' => 'required|string|min:6|confirmed'
        ]);

        $user->update([
            'password' => Hash::make($request->password)
        ]);

        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'update',
            'target_type' => 'user',
            'target_id' => $user->id,
            'content' => "重置用户密码：{$user->username}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('users.index')->with('success', '密码重置成功');
    }

    public function changePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required|string',
            'password' => 'required|string|min:6|confirmed'
        ]);

        $user = Auth::user();

        if (!Hash::check($request->current_password, $user->password)) {
            return back()->withErrors(['current_password' => '当前密码错误']);
        }

        $user->update([
            'password' => Hash::make($request->password)
        ]);

        OperationLog::create([
            'user_id' => $user->id,
            'action' => 'update',
            'target_type' => 'user',
            'target_id' => $user->id,
            'content' => "修改密码",
            'ip' => $request->ip()
        ]);

        return redirect()->route('profile')->with('success', '密码修改成功');
    }

    public function profile()
    {
        return view('users.profile');
    }

    public function logout(Request $request)
    {
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'logout',
            'target_type' => 'user',
            'target_id' => Auth::id(),
            'content' => "用户登出",
            'ip' => $request->ip()
        ]);

        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect()->route('login');
    }
}
